﻿using Common.Domain;
using Common.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Infrastructure.Repository
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 注入上下文
        /// </summary>
        private readonly MyContext myContext;
        public BaseRepository(MyContext myContext)
        {
            this.myContext = myContext;
        }
        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <returns>返回集合</returns>
        public IQueryable<T> GetAll()
        {
            return myContext.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public int Add(T entity)
        {
            myContext.Set<T>().Add(entity);
            return myContext.SaveChanges();
        }
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public int Update(T entity)
        {
            myContext.Set<T>().Update(entity);
            return myContext.SaveChanges();
        }
        /// <summary>
        /// 批量新增数据
        /// </summary>
        /// <param name="entities">实体</param>
        /// <returns>返回受影响行数</returns>
        public int AddRange(IEnumerable<T> entities)
        {
            myContext.Set<T>().AddRange(entities);
            return myContext.SaveChanges();
        }
        /// <summary>
        /// 批量修改数据
        /// </summary>
        /// <param name="entities">实体</param>
        /// <returns>返回受影响行数</returns>
        public int UpdateRange(IEnumerable<T> entities)
        {
            myContext.Set<T>().UpdateRange(entities);
            return myContext.SaveChanges();
        }
        public int Delete(T entity)
        {
            myContext.Set<T>().Remove(entity);
            return myContext.SaveChanges();
        }
        /// <summary>
        /// 导出前查询所有数据
        /// </summary>
        /// <returns></returns>
        //public async  Task<IList<Product>> Export()
        //{
        //    try
        //    {
        //        return await product.GetAllAsync();
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}
    }
}
